package com.zl.registration.module.result;

/**
 * @author zoulei
 * @date 2021/11/16 18:21
 */
public class Result<T> {

    private Integer code;

    private T data;

    private String msg;

    private Result(T data) {
        this.code = 0;
        this.data = data;
        this.msg = "success";
    }

    private Result(CodeMsg codeMsg) {
        if (null == codeMsg) {
            return;
        }
        this.code = codeMsg.getCode();
        this.msg = codeMsg.getMsg();
    }

    private Result(Integer code, String message, T data) {
        this.code = code;
        this.msg = message;
        this.data = data;
    }

    /**
     * 只有get没有set，是为了防止在controller使用set对结果修改，从而达到一个更好的封装效果
     */
    public int getCode() {
        return code;
    }

    /**
     * 业务处理成功返回结果，直接返回业务数据
     */
    public static <T> Result<T> success(T data) {
        return new Result<>(data);
    }

    /**
     * 业务处理信息
     */
    public static <T> Result<T> info(CodeMsg serverError) {
        return new Result<>(serverError);
    }

    /**
     * 业务处理成功
     */
    public static <T> Result<T> success(CodeMsg serverError) {
        return new Result<>(serverError);
    }

    /**
     * 业务处理失败
     */
    public static <T> Result<T> error(CodeMsg serverError) {
        return new Result<>(serverError);
    }

    /**
     * 未登录返回结果
     */
    public static <T> Result<T> unauthorized(T data) {
        return new Result<>(CodeMsg.UNAUTHORIZED.getCode(), CodeMsg.UNAUTHORIZED.getMsg(), data);
    }

    /**
     * 未授权返回结果
     */
    public static <T> Result<T> forbidden(T data) {
        return new Result<>(CodeMsg.FORBIDDEN.getCode(), CodeMsg.FORBIDDEN.getMsg(), data);
    }


    public String getMsg() {
        return msg;
    }

    public T getData() {
        return data;
    }
}
